local assets =
{
    -- Asset("ANIM", "anim/ds_pig_basic.zip"),
    -- Asset("ANIM", "anim/ds_pig_actions.zip"),
    -- Asset("ANIM", "anim/ds_pig_attacks.zip"),
    -- Asset("ANIM", "anim/quagmire_swampig_build.zip"),
    -- Asset("ANIM", "anim/quagmire_swampig_extras.zip"),
    -- Asset("SOUND", "sound/pig.fsb"),
}
local function GetStringsTable()
    return TUNING.NPC_CHAT_TABLE[ type(TUNING.__NPC_LANGUAGE)=="function" and TUNING.__NPC_LANGUAGE() or TUNING.__NPC_LANGUAGE ] ["npc_event_pigman_arena"] or {}
end

local function trans_pigman_skin(pigman)
    pigman.AnimState:SetBank("pigman")
    pigman.AnimState:SetBuild("quagmire_swampig_build") 
    pigman.AnimState:PlayAnimation("idle_loop", true)
    pigman.AnimState:Hide("hat")


    -- pigman.AnimState:OverrideSymbol("pig_arm","quagmire_swampig_build","pig_arm")
    -- pigman.AnimState:OverrideSymbol("pig_arm_trans","quagmire_swampig_build","pig_arm1")
    -- pigman.AnimState:OverrideSymbol("pig_cheeks","quagmire_swampig_build","pig_cheeks")
    -- pigman.AnimState:OverrideSymbol("pig_ear","quagmire_swampig_build","pig_ear")
    -- pigman.AnimState:OverrideSymbol("pig_ear_trans","quagmire_swampig_build","pig_ear1")

    -- pigman.AnimState:OverrideSymbol("pig_head","quagmire_swampig_build","pig_head")
    -- pigman.AnimState:OverrideSymbol("pig_torso","quagmire_swampig_build","pig_torso")

    -- -- local head_random = math.random(11) - 1
    -- -- if head_random == 0 then
    -- -- else
    -- --     pigman.AnimState:OverrideSymbol("pig_head","quagmire_swampig_build","pig_head"..head_random)
    -- -- end

    -- pigman.AnimState:OverrideSymbol("pig_leg","quagmire_swampig_build","pig_leg")
    -- pigman.AnimState:OverrideSymbol("pig_skirt","quagmire_swampig_build","pig_skirt")
    -- -- if head_random == 0 then
    -- -- else
    -- --     pigman.AnimState:OverrideSymbol("pig_torso","quagmire_swampig_build","pig_torso"..head_random)
    -- -- end

    -- pigman.AnimState:OverrideSymbol("were_fur","quagmire_swampig_build","were_fur")    

end
local function Spawn_pigman(inst,num)
    -- local the_pigman = SpawnPrefab("pigman")
    local the_pigman = SpawnPrefab("pigguard")
    ---------------------------------------------------------------------
    ---- 更改外观
    trans_pigman_skin(the_pigman)
    ---------------------------------------------------------------------
    the_pigman.__task = the_pigman:DoPeriodicTask(1,function()
        local the_players = inst:GetPlayers()
        if #the_players > 0 then
            the_pigman.components.combat:SetTarget(the_players[1])
        else
            if the_pigman.__task then
                the_pigman.__task:Cancel()
                the_pigman.__task = nil
            end
            -- the_pigman:RemoveTag("npc_task")
            SpawnPrefab("npc_fx_spawn"):PushEvent("Set",{
                pt = Vector3(the_pigman.Transform:GetWorldPosition())
            })
            the_pigman:Remove()
        end
    end)

    the_pigman.components.lootdropper:SetLoot({"meat", "meat","meat","meat", "meat","meat","meat","pigskin"})
    the_pigman:SetBrain(require "brains/pigguardbrain") ------ 换个脑子
    the_pigman:RestartBrain()                           ------ 重启脑子
    the_pigman.components.werebeast:SetOnWereFn(function() print("--------")  end)  ---- 不会变身

    if num <= 0 then
        num = 1
    end
    the_pigman.components.combat:SetDefaultDamage(TUNING.WEREPIG_DAMAGE * (num*num*10/400 + 1) )    --------- 20个算，1 ~  11倍数上限
    the_pigman.components.health:SetMaxHealth(TUNING.WEREPIG_HEALTH * (num*num*4/400 + 1) )    --- 1 ~ 5 倍血量

    return the_pigman
end


local function arena_event_task(inst)
    -- local pt = Vector3( inst.Transform:GetWorldPosition())
    -- print("Step : ",inst.event_step)
    if inst.event_step == nil then ------------------------------------------------------------------------------- 坐标初始化化
        -------- 第0步，初始化坐标
        inst.__main_stick = inst:SpawnChild("npc_item_pig_head_stick")
        inst.__main_stick:PushEvent("Set",{ pt = Vector3(0,0,0) } )
        inst._stick_heads_num = 20
        inst.__surround_points = inst.npc_base_lib:GetSurroundPoints({ range = 13 , num = inst._stick_heads_num })
        inst._stick_heads = {}
        -- inst.__the_pigman = {}
        inst.event_step = 1

        --------------------------
        ---- 外观包没法加载，试试这个
        TheSim:LoadPrefabs({ "quagmire_swampig" })


    elseif inst.event_step == 1 then -------------------------------------------------------------------------------   第1步，刷一圈猪头
        ----------- 第1步，刷一圈猪头
        if #inst._stick_heads < inst._stick_heads_num then
            local thePoint = inst.__surround_points[#inst._stick_heads + 1]
            local temp_stick = SpawnPrefab("npc_item_pig_head_stick")
            temp_stick:PushEvent("Set",{pt = thePoint})
            inst.npc_base_lib:Add2Child(temp_stick)
            -- inst._stick_heads[i] = temp_stick
            table.insert(inst._stick_heads,temp_stick)
            return
        else
            inst.event_step = 2
        end

    elseif inst.event_step == 2 then -------------------------------------------------------------------------------   第2步，点亮中心的灯
        ------- 第2步，点亮中心的灯
        inst.__main_stick:PushEvent("Set",{awake = true,fire = true})
        inst.__stick_light_on_num = 0
        inst.event_step = 3
    elseif inst.event_step == 3 then -------------------------------------------------------------------------------   第3步，逐个点灯
        ------  第3步，逐个点灯
        if inst.__stick_light_on_num < inst._stick_heads_num then
            inst._stick_heads[inst.__stick_light_on_num + 1]:PushEvent("Set",{awake = true,fire = true})
            inst.__stick_light_on_num = inst.__stick_light_on_num + 1
        else
            inst.event_step = 4
        end
    elseif inst.event_step == 4 then -------------------------------------------------------------------------------   第4步， 刷猪人
        ------- 第4步， 刷猪人
        -- print("light:",inst.__stick_light_on_num)
        local pt = inst.__surround_points[inst.__stick_light_on_num]
        local the_pigman = Spawn_pigman(inst , inst._stick_heads_num - inst.__stick_light_on_num + 1)
        the_pigman:AddTag("npc_task")
        the_pigman.Transform:SetPosition(pt.x,0,pt.z)
        inst.__the_pigman = the_pigman
        ---------------------------------------------------------------------
        inst.event_step = 5
    elseif inst.event_step == 5 then -------------------------------------------------------------------------------   第5步 ，检查玩家 和 猪人状态
        ------ 第5步 ，检查玩家 和 猪人状态
        if not inst.__the_pigman:IsValid() then
            ------ 如果当前出场猪人死了
            inst._stick_heads[inst.__stick_light_on_num]:PushEvent("Set",{awake = false})
            inst.__stick_light_on_num = inst.__stick_light_on_num - 1
            if inst.__stick_light_on_num ~= 0 then  ---- 灯没有到0，继续刷猪人
                inst.event_step = 4
            else
                inst.event_step = 6 ------ 结束了
                -- inst.event_step = 7 ------ 结束了
            end
        end

        local players = inst:GetPlayers()
        if #players == 0 then   -------- 如果没有活着的玩家，进入退出步奏
            inst.event_step = 6
        end
    
    elseif inst.event_step == 6 then -------------------------------------------------------------------------------   第6步，丢奖励  --- 丢复活项链
        ----- 第6步，丢奖励  --- 丢复活项链
        local kill_num = inst._stick_heads_num - inst.__stick_light_on_num

        if inst.__stick_light_on_num < inst._stick_heads_num then
            local gold_num = math.ceil( 0.04 * kill_num * kill_num *kill_num)
            if TUNING.NPC_CONFIG.REWARDS_LESS == true then
                gold_num = math.ceil(gold_num/3)
            end
            inst.npc_base_lib:Throw_Out_Items({
                name = "goldnugget",
                num = gold_num,    -- default
                range = 8, -- default
                height = 5,-- default
                random_height = true
            })
        end

        local playerghost = inst:GetPlayers(true)
        if #playerghost > 0 then
            inst.npc_base_lib:Throw_Out_Items({
                name = "amulet",
                num = #playerghost,    -- default
                range = 8, -- default
                height = 5,-- default
                random_height = true
            })
        end

        if kill_num == inst._stick_heads_num then
            inst.npc_base_lib:Announce(GetStringsTable().success)
        elseif kill_num > 0 then
            inst.npc_base_lib:Announce(GetStringsTable().success_half)
        else
            inst.npc_base_lib:Announce(GetStringsTable().failure)
        end


        inst.event_step = 7
    elseif inst.event_step == 7 then -------------------------------------------------------------------------------   退出删除 第7步
        ---- 退出删除 第7步
        if inst.__stick_light_on_num > 0 then
            inst._stick_heads[inst.__stick_light_on_num]:PushEvent("Set",{awake = false})
            inst.__stick_light_on_num = inst.__stick_light_on_num - 1
        else
            if inst._stick_heads_num > 0 then 
                inst._stick_heads[inst._stick_heads_num]:Remove()
                inst._stick_heads_num = inst._stick_heads_num - 1
            else
                inst:Remove()
            end
        end

    end

end

local function Send_back_to_arena(inst,target)
    local points =  inst.__surround_points
    local pt = points[1]
    local dis = inst.npc_base_lib:Dsitance_T2P(target,pt)
    for i, temp_point in pairs(points) do
        local temp_dis = inst.npc_base_lib:Dsitance_T2P(target,temp_point)
        if temp_dis > dis then
            pt = temp_point
            dis = temp_dis
        end
    end


    -- target.Transform:SetPosition(pt.x,0,pt.z)

    if target.Physics ~= nil then
        target.Physics:Teleport(pt.x, 0, pt.z)
    else
        target.Transform:SetPosition(pt.x,0,pt.z)
    end
end

local function Distance_Limit_and_monster_check_Task(inst)
    local pt = Vector3(inst.Transform:GetWorldPosition())
    local players = TheSim:FindEntities(pt.x, 0, pt.z, 13, {"player"}, {"playerghost"}, nil)
    if inst.____Participant_List == nil then
        inst.____Participant_List = {}
    end

    ----------------- 进来的玩家都加到列表里
    for k, v in pairs(players) do
        inst.____Participant_List[v] = true
    end

    ------------ 限制玩家 范围
    for temp_player,flg in pairs(inst.____Participant_List) do
        if temp_player and temp_player:IsValid() and not temp_player:HasTag("playerghost") then
            if inst.npc_base_lib:Distance_Targets(inst,temp_player) > 13 then
                -- temp_player.Transform:SetPosition(pt.x,0,pt.z)
                Send_back_to_arena(inst,temp_player)
            end
            if temp_player.components.sanity then
                -- temp_player.components.sanity:SetPercent(1) ----- 精神满状态
                temp_player.components.sanity.current = temp_player.components.sanity.max
            end
            if temp_player.components.temperature then  ------- 保证玩家温度
                temp_player.components.temperature:SetTemperature(35)
            end
        end
    end

    ------ 把猪限制在场地内
    if inst.__the_pigman and inst.__the_pigman:IsValid() and inst.npc_base_lib:Distance_Targets(inst,inst.__the_pigman) > 13.5 then
        -- inst.__the_pigman.Transform:SetPosition(pt.x,0,pt.z)     
        Send_back_to_arena(inst,inst.__the_pigman)   
    end

    ----------------------------------------------------------------------------------------------------------------
    -------- 把不相关的家伙弄出去
    local function MonsterOut(monster)
        local temp_pt = inst.npc_base_lib:GetSpawnPoint(inst,20) or Vector3(0,0,0)
        monster.Transform:SetPosition(temp_pt.x,0,temp_pt.z)
        if monster.components.freezable then
            monster.components.freezable:Freeze(300)
        end
    end
    local canthavetags = { "npc_task","companion","isdead","player","INLIMBO", "notarget", "noattack", "flight", "invisible", "playerghost" ,"chester","hutch","wall","structure"}
	local musthavetags = nil
	local musthaveoneoftags = {"pig","rabbit","animal","smallcreature","epic","monster","insect"}
	local monster_insts = TheSim:FindEntities(pt.x, 0, pt.z, 15, musthavetags, canthavetags, musthaveoneoftags)
    if #monster_insts > 0 then
        for k, monster in pairs(monster_insts) do
            if monster and monster:IsValid() then
                if monster.components.combat then
                    if monster.components.combat.target == inst.__the_pigman then
                    --- 助战的怪物不弄出去
                    else
                        MonsterOut(monster)
                    end
                else
                    ---- 没事做的也弄出去
                    MonsterOut(monster)                    
                end
            end
        end
    end

    ----------------------------------------------------------------------------------------------------------------

end

local function fn()
    local inst = CreateEntity()

    inst.entity:AddTransform()
    inst.entity:AddNetwork()

    inst:AddTag("INLIMBO")
    inst:AddTag("FX")
    inst:AddTag("NOBLOCK")
    inst:AddTag("npc_item_pigman_arena_event_start")

    inst.entity:AddLight()

    inst.Light:SetRadius(10)
    -- inst.Light:SetIntensity(0.55)
    inst.Light:SetIntensity(0.7)
    -- inst.Light:SetFalloff(1.3)
    inst.Light:SetFalloff(2)
    inst.Light:SetColour(251/255, 240/255, 218/255)
    inst.Light:Enable(true)

    inst.entity:SetPristine()
    if not TheWorld.ismastersim then
        return inst
    end

    inst:AddComponent("npc_base_lib")

    ----------------------------------------------------------------------------------
    --- 理智光环 --- 好像没啥用
    -- inst:AddComponent("sanityaura")
    -- inst.components.sanityaura.aura = TUNING.SANITYAURA_SUPERHUGE
    -- inst.components.sanityaura.max_distsq = 14*14
    -- inst.components.sanityaura.aurafn =  function()
    --     return TUNING.SANITYAURA_SUPERHUGE
    -- end
    ----------------------------------------------------------------------------------
    inst:ListenForEvent("Set",function(inst,_table)
        -- _table = {
        --     pt = Vector3(0,0,0),
        --     color = Vector3(255,255,255),
        --     a = 0.1,
        --     awake = true
        -- }
        if _table == nil then
            return
        end
        if _table.pt and _table.pt.x then
            inst.Transform:SetPosition(_table.pt.x,_table.pt.y,_table.pt.z)
        end

        inst.Ready = true
    end)

    inst:DoTaskInTime(0,function()
        if inst.Ready ~= true then
            inst:Remove()
        end
    end)
    ----------------------------------------------------------------------------------
    local time = 0.5
    inst:DoPeriodicTask(time,arena_event_task)
    inst:DoPeriodicTask(0.4,Distance_Limit_and_monster_check_Task)


    inst.GetPlayers = function(inst,ghost_flag)
        local pt = Vector3(inst.Transform:GetWorldPosition())
        if ghost_flag ~= true then
            local ents = TheSim:FindEntities(pt.x, 0, pt.z, 15, {"player"}, {"playerghost"}, nil)
            return ents
        else
            local ents = TheSim:FindEntities(pt.x, 0, pt.z, 15, {"playerghost"},nil, nil)
            return ents
        end
    end

    return inst
end

return Prefab("npc_item_pigman_arena_event_start", fn,assets)